﻿using UnityEngine;
using UnityEngine.UI;

namespace UFrame
{
    public class UImageAnimation : MonoBehaviour
    {
        public Image mSR;
        public float mTimer;

        public Sprite[] mSpriteAry;
        private int mIndex = 0;
        private float mStarTimer;

        private bool mIsPlay = false;
        public bool mStartPlay = true;
        public bool mPlayOne = false;
        public int mPlayCount = -1;
        public bool mPlayOneInactive = false;

        private int mPlayCountSign = 0;

        // Use this for initialization
        void Start()
        {
            if (mSR == null)
            {
                mSR = GetComponent<Image>();
            }

            if (mStartPlay)
            {
                Play();
            }
        }

        // Update is called once per frame
        void Update()
        {
            if (mIsPlay)
            {
                if (mSpriteAry.Length == 0)
                {
                    return;
                }

                if (mSR == null)
                {
                    return;
                }

                if (mStarTimer <= Time.time)
                {
                    SetTime();
                    mIndex++;
                    if (mIndex >= mSpriteAry.Length)
                    {
                        mIndex = 0;
                        if (mPlayOne)
                        {
                            mIsPlay = false;
                        }

                        if (mPlayOneInactive)
                        {
                            gameObject.SetActive(false);
                            mIsPlay = false;
                        }

                        if (mPlayCount > 0 && mPlayCountSign >= mPlayCount)
                        {
                            gameObject.SetActive(false);
                            mIsPlay = false;
                            mPlayCountSign = 0;
                        }

                        mPlayCountSign++;
                    }

                    mSR.sprite = mSpriteAry[mIndex];
                }
            }
        }

        private void SetTime()
        {
            mStarTimer = Time.time + mTimer;
        }

        public void Play()
        {
            enabled = true;
            mIsPlay = true;
            SetTime();
        }

        public void StopPlay()
        {
            mIsPlay = false;
        }

        public void Reset()
        {
            mPlayCountSign = 0;
            mIndex = 0;
            mIsPlay = false;
        }
    }
}